package com.library.controller;

import com.library.dto.BookDTO;
import com.library.service.FavoriteService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 收藏控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/books")
@RequiredArgsConstructor
public class FavoriteController {
    private final FavoriteService favoriteService;

    /**
     * 收藏图书接口
     * POST /api/books/{id}/favorite
     */
    @PostMapping("/{id}/favorite")
    public ResponseEntity<Map<String, String>> addFavorite(
            @PathVariable Long id,
            @RequestAttribute Long userId) {
        favoriteService.addFavorite(userId, id);
        Map<String, String> response = new HashMap<>();
        response.put("message", "收藏成功");
        return ResponseEntity.ok(response);
    }

    /**
     * 取消收藏接口
     * DELETE /api/books/favorites/{id}
     */
    @DeleteMapping("/favorites/{id}")
    public ResponseEntity<Map<String, String>> removeFavorite(
            @PathVariable Long id,
            @RequestAttribute Long userId) {
        favoriteService.removeFavorite(userId, id);
        Map<String, String> response = new HashMap<>();
        response.put("message", "取消收藏成功");
        return ResponseEntity.ok(response);
    }

    /**
     * 获取收藏列表接口
     * GET /api/books/favorites
     */
    @GetMapping("/favorites")
    public ResponseEntity<Map<String, List<BookDTO>>> getFavorites(
            @RequestAttribute Long userId) {
        List<BookDTO> favorites = favoriteService.getFavorites(userId);
        Map<String, List<BookDTO>> response = new HashMap<>();
        response.put("books", favorites);
        return ResponseEntity.ok(response);
    }

    /**
     * 检查是否已收藏接口
     * GET /api/books/{id}/favorite
     */
    @GetMapping("/{id}/favorite")
    public ResponseEntity<Map<String, Boolean>> checkFavorite(
            @PathVariable Long id,
            @RequestAttribute Long userId) {
        boolean isFavorite = favoriteService.isFavorite(userId, id);
        Map<String, Boolean> response = new HashMap<>();
        response.put("isFavorite", isFavorite);
        return ResponseEntity.ok(response);
    }
}

